package com.mark.basic.interceptor;

import com.mark.basic.annotation.PreAuthorize;
import com.mark.basic.jwt.JwtUtils;
import com.mark.basic.jwt.Payload;
import com.mark.basic.jwt.RsaUtils;
import com.mark.basic.jwt.UserInfo;
import com.mark.org.mapper.EmployeeMapper;
import com.mark.system.mapper.PermissionMapper;
import com.mark.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${jwt.rsa.pub}")
    private String jwtRsaPub;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置登录拦截
        // 获取token
        String token = request.getHeader("token");
        System.out.println(StringUtils.isEmpty(token));
        // 判断token是否为空
        if (!StringUtils.isEmpty(token)){
            // 解密 jwt
            PublicKey publicKey = RsaUtils
                    .getPublicKey((FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPub))));
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Object loginTmp = userInfo.getUser();

//            Object tokenObj = redisTemplate.opsForValue().get(token);
//            System.out.println(tokenObj);
            if (loginTmp!=null){
//                redisTemplate.opsForValue().set(loginTmp,token,30, TimeUnit.MINUTES);
                // 看是否员工还是前端用户 通过type
                Logininfo tokenObj1 = (Logininfo) loginTmp;
                if (tokenObj1.getType() == 0){
                    // 如果是员工
                    // 1、需要单独校验当前员工，是否有权限访问当前资源
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    // 获取当前请求的资源 preAuthorize
                    // 查询出当前登录人所拥有的资源权限 preAuthorize
                        if(preAuthorize != null) {
                            //3.2 没有，放行  公共资源不需要校验权限
                            //3.1 有，校验是否有权限访问
                            String sn = preAuthorize.value();//需要校验当前登录人，是否有权限访问该资源
                            //查询出当前登录人所拥有的权限
                            List<String> permissions = userInfo.getPermissions();
//                            List<String> ownPermissions = permissionMapper.loadPerssionSnByLogininfoId(tokenObj1.getId());
                            if (permissions.contains(sn)) {
                                return true;//终于有权限访问了
                            }
                            //告诉他没有权限，请他去联系管理员
                            // 如果不在  提示没有权限访问{"success":false ,"message":"noPermission"}
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("application/json;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.print("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                    }
                }
                // 如果是用户，直接放行，不用校验权限
                // 刷新时间
                return true;// 放行   必须放行
            }

        // 当token为空时，说明没有登录
        response.setCharacterEncoding("utf-8"); // 设置字符集
        response.setContentType("application/json; charset=UTF-8");
        // 输出流
        PrintWriter writer = response.getWriter();
//        {"success":false ,"message":"nologin"}
        writer.write("{\"success\":false ,\"message\":\"nologin\"}");
        // 刷新流
        writer.flush();
        // 关闭流
        writer.close();
        return false;
    }
}